﻿using MediatR;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.BasicInformation.MainPlans;
using THE_WIND_RISES.Common.Dtos;

namespace Enterprise_Set.API.Application.Commands.Week2.Mainplan_CRUD
{
    /// <summary>
    /// 显示主生产任务表数据
    /// </summary>
    public class ShowMainplanHander : IRequestHandler<ShowMainplanCommand, Result>
    {
        public ShowMainplanHander(IBaseRepository<Mainpalan> mainpalanRepository)
        {
            MainpalanRepository = mainpalanRepository;
        }

        public IBaseRepository<Mainpalan> MainpalanRepository { get; set; }

        public async Task<Result> Handle(ShowMainplanCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code=(int)CommonErrorCodes.Search};
            var sql = "select * from mainpalans";
            int AddSqlNum = 0;
            if (request.MainplanName != "" || request.MainplanState > 0 || request.MainplanNum != "")
            {
                sql += " where";
                if (!string.IsNullOrEmpty(request.MainplanName))
                {
                    sql += $" MainplanName like('%{request.MainplanName}%');";
                    AddSqlNum++;
                }
                if (request.MainplanState > 0)
                {
                    if (AddSqlNum > 0)
                    {
                        sql += $" and MainplanState ={request.MainplanState};";
                    }
                    else
                    {
                        sql += $" MainplanState ={request.MainplanState};";
                    }
                    AddSqlNum++;
                }
                if (!string.IsNullOrEmpty(request.MainplanNum))
                {
                    if (AddSqlNum > 0)
                    {
                        sql += $" and MainplanNum like('%{request.MainplanNum}%');";
                    }
                    else
                    {
                        sql += $" MainplanNum like('%{request.MainplanNum}%');";
                    }
                }
                sql += " and IsDelMainplan==false;";
            }
            else
            {
                sql += " where IsDelete=false;";
            }
            var list = MainpalanRepository.GetAll(sql).ToList();
            if (list != null)
            {
                int count = list.Count();
                int znum = Convert.ToInt32(Math.Ceiling((double)count / request.qnum));
                list = list.OrderBy(x => x.MainplanId).Skip((request.ynum - 1) * request.qnum).Take(request.qnum).ToList();
                result.Data = new { data=list,count=count,znum=znum} ;
                result.Code = (int)CommonErrorCodes.Success;
                return result;
            }
            else
            {
               return result;
            }
        }
    }
}
